<?php

namespace app\common\library\job;

use app\admin\model\User;
use think\Log;
use think\queue\Job;
use think\Db;


class ReleaseIncomeJob extends BaseJob

{

     /**
      * 创建任务
      * 
      * $data['logId']  任务订单id
      *  \think\Queue::push(('\app\common\library\job\ReleaseIncomeJob@createLog', $data, 'ReleaseIncome');
      * 
     */
    
    public function createLog(Job $job, $data){
        try {
            $taskId = $data['logId'];
            $task = Db::name("job_task")->where("id", $taskId)->find();
            if(empty($task) || $task['status'] !=0){
                // 删除 job
                echo date("Y-m-d H:i:s")." 任务ID:{$taskId} 状态:{$task['status']} 任务删除";
                $job->delete();
            }
            $DiLevelMoney= User::DiLevelMoney($task['total_money']);
//            var_dump($DiLevelMoney);

            $page = 1;
            $time = time();
            $lastId = $task['last_id'];
            do{
                $list = Db::name("user")->whereIn("user_level", [1,2,3,4,5,6])->order('id ASC')->page($page,50)->select();
                var_dump($list);
                $dataSet = [];

                foreach ($list as $user) {
                    //处理记录
                    $lastId = $user['id'];
                    $temp = [];
                    $temp['user_id'] = $user['id'];
                    $temp['level'] = $user['user_level'];
                    $temp['type'] = 1;
                    $temp['money'] = empty($user['user_level'])?0:@$DiLevelMoney[$user['user_level']];
                    $temp['add_time'] = $time;
                    $temp['status'] = 0;
                    $temp['month'] = $task['month'];
                    var_dump($temp);
                    $dataSet = $temp;
                }
                Db::transaction(function () use ($taskId, $dataSet,$lastId) {
                    Db::name('user_weighting_score_detail')->insertAll($dataSet);
                    Db::name('job_task')->where(['id'=>$taskId])->update(['update_time'=>time(),'last_id'=>$lastId,'status'=>2]);
                });
                $page++;
            }while(!empty($list));
            Db::name('job_task')->where(['id'=>$taskId])->update(['update_time'=>time(),'last_id'=>$lastId,'status'=>1]);

            // 删除 job
            $job->delete();
        } catch (\Exception $e) {
//            var_dump($e);
            echo "分佣失败！".$e->getMessage().'行：'.$e->getFile().':'.$e->getLine().PHP_EOL;
            \think\Log::write("分佣失败！".$e->getMessage().'行：'.$e->getFile().':'.$e->getLine());
            $job->delete();
            // 队列执行失败
//            if ($job->attempts() > 3) {
//                 $job->failed($data);
//            }
//            //延迟2秒后再执行
//             $job->release(2);
        }
    }

}
